<template>
    <div class="app-container">
        <section>
            <div class="contentBox">
                <div class="content">
                    <div class="title">
                        <span>{{ $route.query.title }}</span>
                        <i class="el-icon-close" @click="$router.go(-1)" v-if="$route.query.title == '详情'"></i>
                    </div>
                    <el-form ref="form" class="myfrom" label-position="top" :model="form" label-width="120px" :rules="rules">
                        <el-form-item label="产品标题" prop="name">
                            <el-input v-model="form.name" style="width: 600px" placeholder="请输入内容" :readonly="$route.query.title == '详情'"></el-input>
                        </el-form-item>
                        <el-row :gutter="10">
                            <el-col :span="6">
                                <el-form-item label="产品缩略图" prop="images" :rules="[
                    {
                      required: true,
                      message: '请上传产品缩略图',
                      trigger: 'change',
                    },
                  ]">
                                    <div class="img" v-if="form.images">
                                        <el-image :src="form.images" :lazy="true" fit="fill" style="width: 100%;  height: 100%" :preview-src-list="form.srcList">
                                            <div slot="error" class="image-slot" style="
                          width: 100%;
                          height: 100%;
                          background-color: #e6e6e6;
                        "></div>
                                        </el-image>
                                        <i class="el-icon-delete" @click="form.images = ''" v-if="$route.query.title != '详情'"></i>
                                    </div>
                                    <el-upload :action="$Reg.uploadUrl" list-type="picture-card" :http-request="okUpload" :data="{ flag: (a = 'a') }" v-else :show-file-list="false">
                                        <i class="el-icon-plus"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                            <el-col :span="18">
                                <el-form-item label="产品细节图">
                                    <div v-if="$route.query.title == '详情'" style="display: flex">
                                        <div v-for="(item, index) in form.picture" :key="index" style="
                        width: 146px;
                        height: 146px;
                        margin-right: 10px;
                        border-radius: 10px;
                      ">
                                            <el-image :src="item.url" :lazy="true" fit="fill" style="width: 100%;  height: 100%" :preview-src-list="form.srcList1">
                                                <div slot="error" class="image-slot" style="
                            width: 100%;
                            height: 100%;
                            background-color: #e6e6e6;
                          "></div>
                                            </el-image>
                                        </div>
                                    </div>
                                    <el-upload :action="$Reg.uploadUrl" list-type="picture-card" :file-list="form.picture" :data="{ flag: (a = 'b') }" :http-request="okUpload" :on-remove="remove" v-else :on-preview="preview">
                                        <i class="el-icon-plus"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="商品规格">
                            <el-button type="primary" icon="el-icon-plus" @click="handleSpecShow">新增规格</el-button>
                            <el-button type="success" icon="el-icon-coin" @click="choose" :disabled="!form.id ? false : true">一键生成(价格&库存)表</el-button>
                        </el-form-item>
                        <el-table ref="multipleTable" :data="list" tooltip-effect="dark" border empty-text="没有数据，请先添加规格，建议规格不超过4组！" :header-cell-style="{ background: '#f5f6f8' }">
                            <el-table-column prop="name" label="规格"> </el-table-column>
                            <el-table-column label="规格值">
                                <template slot-scope="scope">
                                    <el-checkbox-group v-model="checkList[scope.$index].list">
                                        <!-- @change="choose($event,scope.row,scope.$index)" -->
                                        <el-checkbox :label="item" v-for="(item, index) in scope.row.list" :key="index"></el-checkbox>
                                    </el-checkbox-group>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="330">
                                <template slot-scope="scope">
                                    <el-button @click="handleClick(scope.row, 0, scope.$index)" size="mini" style="margin-right: 15px">编辑</el-button>
                                    <el-popconfirm title="确定删除吗 ？" @onConfirm="handleClick(scope.row, 1, scope.$index)">
                                        <el-button @onConfirm="handleClick(scope.row, 1, scope.$index)" slot="reference" size="mini" type="danger">删除</el-button>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-form-item label="价格&库存">
                            <el-button type="primary" icon="el-icon-plus" @click="addPriceBtn">新增一条</el-button>
                        </el-form-item>
                        <el-table ref="multipleTable" :data="tableData" size="mini" tooltip-effect="dark" border :header-cell-style="{ background: '#f5f6f8' }">
                            <!-- <el-table-column
                v-for="(col, index) in cols"
                :prop="col.prop"
                :label="col.label"
                :key="index"
              > 
              </el-table-column>
              -->
                            <el-table-column label="规格名称" prop="sku_text">
                            </el-table-column>

                            <el-table-column label="售价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.sale_price" size="small" placeholder="售价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="普通会员价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.merber_price" size="small" placeholder="普通会员价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="金卡会员价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.gold_price" size="small" placeholder="金卡会员价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="黑金卡会员价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.black_gold_price" size="small" placeholder="黑金卡会员价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="一级经销商价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.one_dealer_price" size="small" placeholder="一级经销商价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="二级经销商价">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.two_dealer_price" size="small" placeholder="二级经销商价" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.stock" placeholder="库存" size="small" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="排序">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.sort" placeholder="排序" size="small" type="number" :min="0"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="图片">
                                <template slot-scope="scope">
                                    <div style="transform:scale(0.6)">
                                        <div class="img" v-if="scope.row.img">
                                            <el-image :src="scope.row.img" :lazy="true" fit="fill" style="width: 100%;  height: 100%" :preview-src-list="scope.row.srcList">
                                                <div slot="error" class="image-slot" style="
                          width: 100%;
                          height: 100%;
                          background-color: #e6e6e6;
                        "></div>
                                            </el-image>
                                            <i class="el-icon-delete" @click="scope.row.img = ''"></i>
                                        </div>
                                        <el-upload :action="$Reg.uploadUrl" list-type="picture-card" :http-request="okUpload" :data="{ flag: (a = scope.$index) }" v-else :show-file-list="false">
                                            <i class="el-icon-plus"></i>
                                        </el-upload>
                                    </div>

                                </template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <!-- <el-popconfirm
                    title="确定删除吗 ？"
                    @onConfirm="delTableData(scope.$index)"
                  > -->
                                    <el-button @click="delTableData(scope.$index)" type="danger" slot="reference" size="small">删除</el-button>
                                    <!-- </el-popconfirm> -->
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-form-item label="产品描述" style="width: 100%" prop="details" :rules="[
                { required: true, message: '请输入产品描述', trigger: 'blur' },
              ]">
                            <div id="edit1" ref="edit1"></div>
                        </el-form-item>
                    </el-form>
                    <div v-if="$route.query.title != '详情'">
                        <el-button type="primary" style="width: 143px" @click="save">确定</el-button>
                        <el-button style="width: 143px" @click="$router.go(-1)">取消</el-button>
                    </div>
                </div>
            </div>
            <el-dialog title="请选择规格" width="20%" :visible.sync="addPriceFlag">
                <el-form label-position="left" class="myoptfrom">
                    <el-form-item :label="item.name" v-for="(item, index) in optList" :key="index">
                        <el-select v-model="item.value" placeholder="请选择">
                            <el-option :label="ele.value" :value="ele.value" v-for="(ele, key) in item.listArr" :key="key"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addPriceConfirm">确 定</el-button>
                </span>
            </el-dialog>
            <el-dialog :title="title + '规格属性'" :visible.sync="specShow" width="30%">
                <el-form ref="form" :model="spec" label-width="180px" class="myfrom">
                    <el-form-item prop="specName" label="规格名">
                        <el-input v-model="spec.specName" placeholder="请输入规格名称" style="width: 200px"></el-input>
                    </el-form-item>
                    <el-form-item prop="specVal" label="规格值（回车键新增）">
                        <el-input @keyup.enter.native="addSpecVal" v-model="spec.specVal" placeholder="请输入规格值" style="width: 200px"></el-input>
                        <el-button type="success" style="margin-left: 10px" @click="addSpecVal">新增</el-button>
                    </el-form-item>
                    <el-tag v-for="(tag, index) in spec.tags" :key="index" closable type="success" style="margin-right: 5px" @close="spec.tags.splice(spec.tags.indexOf(tag), 1)">
                        {{ tag }}
                    </el-tag>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addSpecList">确 定</el-button>
                </span>
            </el-dialog>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
        </section>
    </div>
</template>

<script>
import E from "wangeditor";
export default {
    data() {
        return {
            dialogVisible: false,
            dialogImageUrl: "",
            editor1: "",
            cols: [],
            tableData: [],
            title: "新增",
            specShow: false,
            flag: {
                a: "a",
            },
            list: [
                // { name: '尺码', list: ['S', 'M', 'L', 'XL', 'XXL'] },
                // { name: '颜色', list: ['红色', '黄色', '蓝色', '粉色', '紫色'] },
                // { name: '图案', list: ['猫咪', '人物', '飞机', '闪电', '字母'] }
            ],
            checkList: [
                // { name: '尺码', list: [] },
                // { name: '颜色', list: [] },
                // { name: '图案', list: [] }
            ],
            form: {
                name: "",
                images: "",
                id: "",
                details: "",
                picture: [],
            },
            spec: {
                specName: "",
                specVal: "",
                tags: [],
            },
            rules: {
                name: [{ required: true, message: "请输入产品标题", trigger: "blur" }],
            },
            select: [],
            companyList: [],
            specIndex: 0, //规格下标
            specRowIndex: 0, //规格行下标
            skuArray: [],
            skuList: [],
            addPriceFlag: false,
            optList: "",
        };
    },
    created() {
        if (this.$route.query.id) {
            this.form.id = this.$route.query.id;
            this.getDetail();
        } else {
        }
        this.$route.meta.title = this.$route.query.title
    },
    mounted() {
        if (!this.form.id) {
            this.getEdit();
        }
    },
    methods: {
        preview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        addPriceConfirm() {
            let cols = [];
            let sku_text = ''
            this.optList.forEach((item, index) => {
                sku_text += item.name + ':' + item.value + ';'
            });
            let obj = {
                sku_text,
                sku_id: "",
                stock: "",
                img: "",
                sort: "",
                sale_price: "",
                merber_price: "",
                black_gold_price: "",
                gold_price: "",
                one_dealer_price: "",
                two_dealer_price: "",
            };

            this.tableData.push(obj);
            this.optList = [];
            this.cols = cols;
            this.addPriceFlag = false;
        },
        addPriceBtn() {
            // 添加一条sku
            console.log("this.list :>> ", this.list);
            if (!this.list.length) {
                this.$message.warning("请先添加规格");
                this.specShow = true;
                return false;
            }
            let optList = [];
            this.list.forEach((item, index) => {
                let { name, list } = item;
                let listArr = [];
                for (let key in list) {
                    listArr.push({
                        value: list[key],
                        label: list[key],
                    });
                }
                optList.push({ name, listArr, value: listArr[0].value });
            });
            this.optList = optList;
            this.addPriceFlag = true;
        },
        delTableData(index) {
            this.tableData.splice(index, 1);
            this.$forceUpdate();
        },
        remove(file, fileList) {
            this.form.picture = fileList;
        },
        choose() {
            // 先清空数据，保证连续点击按钮，数据不会重复
            this.skuArray = [];
            this.skuList = [];
            this.cols = [];
            this.tableData = [];
            console.log('this.checkList :>> ', this.checkList);
            let chooseArr = []
            this.checkList.forEach((item, index) => {
                let str = ''
                let newArr = []
                item.list.forEach((ele, key) => {
                    str = item.name + ':' + ele
                    newArr.push(str)
                })
                chooseArr.push(newArr)
            })
            let resArr = this.getCombination(chooseArr) // 生成排列组合
            console.log("🤬 ~ choose ~ resArr", resArr)
            resArr.forEach((item, index) => {
                this.tableData.push({
                    sku_text: item.join(';'),
                    sku_id: "",
                    stock: "",
                    img: "",
                    sort: "",
                    sale_price: "",
                    merber_price: "",
                    black_gold_price: "",
                    gold_price: "",
                    one_dealer_price: "",
                    two_dealer_price: "",
                })
            })

        },
        getCombination(array) {
            let resultArr = [];
            array.forEach((arrItem) => {
                if (resultArr.length === 0) {
                    let firstItem = [];
                    arrItem.forEach(item => {
                        firstItem.push([item]);
                    })
                    resultArr = firstItem
                } else {
                    const emptyArray = [];
                    resultArr.forEach((item) => {
                        arrItem.forEach((value) => {
                            emptyArray.push([...item, value])
                        })
                    })
                    resultArr = emptyArray
                }
            });
            return resultArr;
        },
        // 递归获取每条SKU数据
        handleClick(row, flag, index) {
            this.specIndex = index;
            if (flag == 0) {
                //编辑
                this.title = "编辑";
                this.spec.specName = JSON.parse(JSON.stringify(row.name));
                this.spec.tags = JSON.parse(JSON.stringify(row.list));
                this.specShow = true;
            } else {
                //删除
                this.list.splice(index, 1);
                console.log(row);
                for (let i in this.checkList) {
                    if (this.checkList[i].name == row.name) {
                        this.checkList.splice(i, 1);
                    }
                }
                this.choose();
            }
        },
        addSpecList() {
            if (!this.spec.specName) {
                this.$message.warning("请输入规格名");
                return;
            }
            if (!this.spec.tags.length) {
                this.$message.warning("至少输入一个规格值");
                return;
            }
            console.log(this.spec);
            if (this.title == "新增") {
                this.list.push({ name: this.spec.specName, list: this.spec.tags });
                this.checkList.push({ name: this.spec.specName, list: [] });
            } else {
                console.log(this.specIndex);
                this.list[this.specIndex].name = this.spec.specName;
                this.list[this.specIndex].list = this.spec.tags;
            }
            console.log(this.list);
            this.specShow = false;
        },
        //新增规格值列表
        addSpecVal() {
            if (!this.spec.specName) {
                this.$message.warning("至少输入一个规格值");
                return;
            }
            this.spec.tags.unshift(this.spec.specVal);
            this.spec.specVal = "";
        },
        handleSpecShow() {
            this.spec.tags = [];
            this.spec.specName = "";
            this.spec.specVal = "";
            this.specShow = true;
        },
        async getDetail() {
            this.loading = true;
            let res = await this.$Http.getInfoGoods({ id: this.form.id });
            if (res.status == 1) {
                let info = JSON.parse(JSON.stringify(res.data));
                this.checkList = info.checkList ? JSON.parse(info.checkList) : [];
                this.tableData = info.sku;
                this.form.name = info.title;
                this.form.images = info.images;
                this.list = info.attr;
                console.log(this.list)
                info.picture = info.picture.split(",");
                this.form.srcList = [this.form.images];
                for (let i in info.picture) {
                    this.form.picture.push({ url: info.picture[i] });
                }
                this.form.srcList1 = info.picture;
                for (let i in this.list) {
                    // console.log(this.list[i])
                    this.list[i].list = [];
                    for (let j in this.list[i].val) {
                        this.list[i].list.push(this.list[i].val[j].attr_value);
                    }
                }
                for (let i in info.sku) {
                    info.sku[i].list = [];
                    info.sku[i].list = info.sku[i].sku_text.split("；");
                    info.sku[i].list.pop();
                }
                for (let i in this.checkList) {
                    this.cols.push({
                        prop: `val${i}`,
                        label: `${this.checkList[i].name}`,
                    });
                }
                // this.choose()
                this.form.details = info.details;
                this.getEdit();
                for (let i in this.tableData) {
                    this.tableData[i].srcList = [this.tableData[i].img];
                }
                // this.choose()
            }
            this.loading = false;
        },
        save() {
            let form = JSON.parse(JSON.stringify(this.form));
            form.checkList = this.checkList ? JSON.stringify(this.checkList) : [];
            form.content = JSON.stringify(this.tableData);
            let arr = [];
            for (let i in this.form.picture) {
                arr.push(this.form.picture[i].url);
            }
            form.picture = arr.join(",");
            console.log(this.tableData)
            for (let i in this.tableData) {
                if (this.tableData[i].sale_price === '') {
                    return this.$message.warning('请输入售价')
                }
                if (this.tableData[i].merber_price === '') {
                    return this.$message.warning('请输入普通会员价')
                }
                if (this.tableData[i].black_gold_price === '') {
                    return this.$message.warning('请输入黑金卡会员价')
                }
                if (this.tableData[i].gold_price === '') {
                    return this.$message.warning('请输入金卡会员价')
                }
                if (this.tableData[i].one_dealer_price === '') {
                    return this.$message.warning('请输入一级经销商价')
                }
                if (this.tableData[i].two_dealer_price === '') {
                    return this.$message.warning('请输入二级经销商价')
                }
                if (this.tableData[i].stock === '') {
                    return this.$message.warning('请输入库存')
                }
            }
            form.title = form.name;
            form.attr = JSON.stringify(this.list);
            form.spec = JSON.stringify(this.tableData);
            console.log("🤬 ~ save ~ orm.spec ", form.spec)

            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    let res = await this.$Http.saveGoods(form);
                    if (res.status == 1) {
                        if (this.form.id) {
                            this.$message.success("编辑成功");
                        } else {
                            this.$message.success("添加成功");
                        }
                        this.$router.push("/productManagement/productList");
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        //上传头像文件等
        okUpload(file) {
            console.log(file);
            let formData = new window.FormData();
            formData.append("files", file.file);
            console.log(formData);
            this.$Http.upload(formData).then((res) => {
                console.log(res);
                if (res.status == 1) {
                    this.$message({ message: "上传成功", type: "success" });
                    if (file.data.flag == "a") {
                        this.form.images = res.data;
                    } else if (file.data.flag == "b") {
                        this.form.picture.push({ url: res.data });
                    } else {
                        for (let i in this.tableData) {
                            if (i == file.data.flag) {
                                this.tableData[i].img = res.data;
                            }
                        }
                    }
                } else {
                    this.$message(res.msg);
                }
            });
        },
        getEdit() {
            this.editor1 = new E(this.$refs.edit1);
            // editor1.txt.clear()
            // console.log(this.form.type0content)
            // 或者 const editor = new E( document.getElementById('div1') )
            this.editor1.config.onchange = (html) => {
                this.form.details = html;
            };
            // editor.config.uploadImgServer = this.$Reg.uploadUrl
            this.editor1.config.customUploadImg = (resultFiles, insertImgFn) => {
                console.log(resultFiles);
                let formData = new window.FormData();
                formData.append("files", resultFiles[0]);
                this.$Http.upload(formData).then((res) => {
                    console.log(res);
                    if (res.status == 1) {
                        this.$message({
                            message: "上传成功",
                            type: "success",
                        });
                        insertImgFn(res.data);
                    } else {
                        this.$message(res.msg);
                    }
                });
            };
            this.editor1.config.customUploadVideo = (resultFiles, insertVideoFn) => {
                let formData = new window.FormData();
                formData.append("files", resultFiles[0]);
                this.$Http.upload(formData).then((res) => {
                    console.log(res);
                    if (res.status == 1) {
                        this.$message({
                            message: "上传成功",
                            type: "success",
                        });
                        insertVideoFn(res.data);
                    } else {
                        this.$message(res.msg);
                    }
                });
            };
            this.editor1.create();
            this.editor1.txt.html(this.form.details);
        },
    },
};
</script>

<style lang="scss" scoped>
.app-container {
    ::v-deep .w-e-toolbar {
        z-index: 1000 !important;
    }
    ::v-deep .w-e-text-container {
        z-index: 1 !important;
    }
    // ::v-deep .el-form-item__label {
    //     float: initial;
    // }
    ::v-deep .el-input.is-disabled .el-input__inner {
        color: #606266;
        background-color: transparent;
    }
    ::v-deep input::-webkit-outer-spin-button,
    ::v-deep input::-webkit-inner-spin-button {
        -webkit-appearance: none !important;
    }
    ::v-deep input[type="number"] {
        -moz-appearance: textfield !important;
    }
    .kong {
        height: 40px;
    }
    .img {
        width: 146px;
        height: 146px;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 3s;
        &:hover {
            i {
                display: flex;
                align-items: center;
                justify-content: center;
                background: rgba($color: #000000, $alpha: 0.3);
                color: rgba($color: #fff, $alpha: 1);
            }
        }
        i {
            position: absolute;
            color: #fff;
            font-size: 26px;
            display: none;
        }
    }
    .myoptfrom {
        display: flex;
        justify-content: center;
        flex-direction: column;
    }
    section {
        background: #eee;
        padding: 30px;
        .contentBox {
            background: #fff;
            border-radius: 8px;
            padding: 0 24px 20px;
        }

        .content {
            // width: 517px;
            height: 100%;
            .title {
                height: 65px;
                font-size: 18px;
                font-weight: 600;
                color: #383b40;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .el-icon-close {
                    cursor: pointer;
                }
            }
        }
    }
}
</style>